package cn.wit.summit.chwan.ui.activity;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.adapters.GreatCrackAdapter;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dto.GameInfoDetialV2Bean;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.response.GreatCrackCollectionResponse;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.base.BaseActivity;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.widgets.DownloadViewStrokeV2;
import cn.wit.summit.chwan.widgets.DownloadViewStrokeV2Big;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/7/19.
 */

public class GreatCrackActivity extends BaseActivity {

    @Bind(R.id.greatCrackBackIv)
    ImageView greatCrackBackIv;
    @Bind(R.id.greatCrackTopIv)
    ImageView greatCrackTopIv;
    @Bind(R.id.greatCrackTitleTv)
    TextView greatCrackTitleTv;
    @Bind(R.id.greatCrackTopRl)
    RelativeLayout greatCrackTopRl;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private String titleStr;
    private String collectionId;

    private GreatCrackAdapter adapter;
    private List<GreatCrackAdapter.ViewBean> mDatas = new ArrayList<>();
    private LinearLayoutManager layoutManager;

    private int totalDy = 0;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    private int pn = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_great_crack);
        ButterKnife.bind(this);

        topLayout.setVisibility(View.GONE);

        titleStr = getIntent().getStringExtra("title");
        collectionId = getIntent().getStringExtra("collection_id");

        retrofitManager = RetrofitManager.getInstance(mContext);
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);

        setTopViewAlpha(0);
        initListView();
    }

    private void initListView() {
        adapter = new GreatCrackAdapter(mAty, mDatas);
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        refreshLayout.setOnRefreshListener(new cn.wit.summit.chwan.widgets.refreshLayout.listener.OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                pn = 1;
                getData();
            }
        });
        refreshLayout.setOnLoadMoreListener(new cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                getData();
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                totalDy += dy;
                setTopViewAlpha(totalDy);
            }
        });

        showSkeleton();
        pn = 1;
        getData();
    }

    private void setTopViewAlpha(int totalDy) {
        float alpha = totalDy / 310f;

//        Drawable barBg = greatCrackTopRl.getBackground();
        if (alpha == 0f) {
//            barBg.setAlpha(0);
            greatCrackTopIv.setAlpha(0);
            greatCrackTitleTv.setAlpha(0f);
            greatCrackBackIv.setImageResource(R.mipmap.game_detail_v2_back_ic);
        } else if (alpha >= 1.0f) {
//            barBg.setAlpha(255);
            greatCrackTopIv.setAlpha(255);
            greatCrackBackIv.setImageResource(R.mipmap.back_icon);
            greatCrackTitleTv.setAlpha(1f);
        } else {
            greatCrackBackIv.setImageResource(R.mipmap.game_detail_v2_back_ic);
//            barBg.setAlpha((int) (alpha * 255));
            greatCrackTopIv.setAlpha((int) (alpha * 255));
            greatCrackTitleTv.setAlpha(alpha);
        }
//        greatCrackTopRl.setBackgroundDrawable(barBg);
    }

    private void getData() {
        api.greatCrackCollection(retrofitManager.greatCrackCollectionRequest(collectionId, pn)).enqueue(new MyCallback<ResponseBase<GreatCrackCollectionResponse>>() {
            @Override
            public void onSuccess(ResponseBase<GreatCrackCollectionResponse> model) {
                hideSkeleton();
                updataUi(model.getData_info());
            }

            @Override
            public void onFailure(int code, String msg) {
                if (code==-4){
                    if (pn == 1) {
                        refreshLayout.finishRefresh();
                    } else {
                        refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                    }
                } else {
                    refreshLayout.finishLoadMore(false);
                    refreshLayout.finishRefresh();
                    hideSkeleton();
                    showToast(msg);
                }
            }
        });
    }

    private void updataUi(GreatCrackCollectionResponse data) {
        if (data == null || data.getCollection_game_list()==null || data.getCollection_game_list().size()==0) {
            if (pn == 1) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
            }
            return;
        }

        if (pn == 1) {
            adapter.clearTempData();
            mDatas.clear();

            greatCrackTitleTv.setText(data.getCollection_title());
            mDatas.add(new GreatCrackAdapter.ViewBean(GreatCrackAdapter.ViewType.TYPE_TOP, data));
        }


        List<GameInfoDetialV2Bean> dataLits = data.getCollection_game_list();
        for (int i=0;dataLits!=null && i<dataLits.size();i++) {
            if (i>0) {
                mDatas.add(new GreatCrackAdapter.ViewBean(GreatCrackAdapter.ViewType.TYPE_LINE));
            }
            mDatas.add(new GreatCrackAdapter.ViewBean(GreatCrackAdapter.ViewType.TYPE_GAME, dataLits.get(i)));
            mDatas.add(new GreatCrackAdapter.ViewBean(GreatCrackAdapter.ViewType.TYPE_GAME_CRACK, dataLits.get(i)));
        }

        adapter.notifyDataSetChanged();

        if (refreshLayout != null) {
            if (data == null || data.getCollection_game_list() == null
                    || data.getCollection_game_list().size() == 0) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                if (pn == 1)
                    refreshLayout.finishRefresh();
                else
                    refreshLayout.finishLoadMore();
                pn += 1;
            }
        }
    }

    @OnClick({R.id.greatCrackBackIv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.greatCrackBackIv:
                finish();
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent downloadEvent) {
//        recommendTopDownloadTop.setTotalDownloadNum();//设置下载数

        String str = adapter.getPoByGameId(downloadEvent.getGameId());
        if (!StringUtils.isEmpty(str)) {
            GameListBaseBean bean = adapter.getBeanData(Integer.valueOf(str), 0);
            if (bean == null) return;
            DownLoadTaskTable table = bean.getTaskTable();
            if (table == null) {
                table = bean.getDownloadTaskTableSimple();
            }
            table.setDownStatus(downloadEvent.status);
            if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                table.setDownprogress(downloadEvent.getProgress());
            }

            View view = layoutManager.findViewByPosition(Integer.valueOf(str));

            DownloadViewStrokeV2 dowView = view.findViewById(R.id.itemDownloadBtn);
            if (dowView != null) {
                dowView.updateButn(table);
            }
        }
    }

    @Override
    public void reGetData() {
        super.reGetData();
        pn = 1;
        getData();
    }

    @Override
    protected int getSkeletonLayoutId() {
        return R.layout.activity_game_starter_skeleton;
    }
}
